/*
 * @lc app=leetcode.cn id=101 lang=java
 *
 * [101] 对称二叉树
 */

// @lc code=start

import java.util.Queue;
import java.util.LinkedList;


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // public boolean isSymmetric(TreeNode root) {
    //     if(root==null){
    //         return true;
    //     }
    //     return compare(root.left,root.right);
    // }

    // private boolean compare(TreeNode left, TreeNode right) {
    //     if(left == null && right != null) {
    //         return false;
    //     }
    //     if(left != null && right == null) {
    //         return false;
    //     }

    //     if(left == null && right == null) {
    //         return true;
    //     }

    //     if(left.val != right.val) {
    //         return false;
    //     }

    //     boolean outside = compare(left.left, right.right);
    //     boolean inside = compare(left.right, right.left);
    //     return outside && inside;
    // }

    public boolean isSymmetric(TreeNode root) {
        if(root==null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root.left);
        queue.offer(root.right);

        while(!queue.isEmpty()) {
            TreeNode leftNode = queue.poll();
            TreeNode rightNode = queue.poll();

            if(leftNode == null && rightNode == null) {
                continue;
            }

            if(leftNode == null || rightNode == null || leftNode.val != rightNode.val) {
                return false;
            }

            // 两两对称放入队列
            queue.offer(leftNode.left);
            queue.offer(rightNode.right);

            queue.offer(leftNode.right);
            queue.offer(rightNode.left);
        }

        return true;
    }
}
// @lc code=end

